﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project.Co_DataTransformationPrototype
{
    public class CRMModelPublisher : ModelPublisher
    {
        private ModelRoot modelRoot;

        public CRMModelPublisher(ModelRoot modelRoot)
        {
            this.modelRoot = modelRoot;
        }

        public override void publishModel()
        {
            // Get a list of all modified entities
            IList<Entity> entityList = getAllModifiedEntities();

            // Create Staging Database
            createStagingDB(entityList);

            // TODO: Apply database script to staging dbase

            // TODO: Publish metadata to server

            // TODO: Update the needed entities and their attributes
        }

        public override void createStagingDB(IList<Entity> entityList)
        {
            // Ensure proper schema name
            if (!temp.StagingDatabase.selectDatabaseSchema())
                temp.StagingDatabase.createDatabaseSchema();

            // Ensure metadata tables for CRM entities and attributes exist
            if (!temp.StagingDatabase.checkForMetadataTables())
            {
                temp.StagingDatabase.createMetadataTables(Data.DatabaseSettings.resourceMetadataScriptPathString);
            }

            temp.StagingDatabase.createStagingDatabase(entityList, CRMModelBuilder.GetInstance(modelRoot).CRMEntityCollection);
        }

        public override IList<Entity> getAllModifiedEntities()
        {
            IList<Entity> entityList = new List<Entity>();
            foreach (KeyValuePair<Guid,ElementEventInfo> item in EventLogger.GetInstance().EventCollection)
            {
                Entity ent = (modelRoot.Store.ElementDirectory.FindElement(item.Key) as Entity);
                if ( ent != null && item.Value.entityState.stateType != StateType.Imported)
                    entityList.Add(ent);
            }
            return entityList;
        }

    }
}
